<script lang="ts">
	import { toast } from 'svelte-sonner';
	import { onMount, getContext } from 'svelte';

	import { user } from '$lib/stores';
	import { updateUserProfile, createAPIKey, getAPIKey } from '$lib/apis/auths';

	import UpdatePassword from './Settings/Account/UpdatePassword.svelte';
	import { getGravatarUrl } from '$lib/apis/utils';
	import { generateInitialsImage, canvasPixelTest } from '$lib/utils';
	import { copyToClipboard } from '$lib/utils';
	import Plus from '$lib/components/icons/Plus.svelte';
	import Tooltip from '$lib/components/common/Tooltip.svelte';
	import Modal from '../common/Modal.svelte';

	const i18n = getContext('i18n');

	export let show = false;
	let profileImageUrl = '';
	let name = '';

	let profileImageInputElement: HTMLInputElement;

	const submitHandler = async () => {
		if (name !== $user.name) {
			if (profileImageUrl === generateInitialsImage($user.name) || profileImageUrl === '') {
				profileImageUrl = generateInitialsImage(name);
			}
		}

		const updatedUser = await updateUserProfile(localStorage.token, name, profileImageUrl).catch(
			(error) => {
				toast.error(error);
			}
		);

		if (updatedUser) {
			await user.set(updatedUser);
			return true;
		}
		return false;
	};

	onMount(async () => {
		name = $user.name;
		profileImageUrl = $user.profile_image_url;
	});
</script>

<Modal bind:show size='sm'>
	<div class="bg-[#374151] text-[#f7f7f7] rounded-xl">
		<div class=" flex justify-between px-5 py-4">
			<div class=" text-lg font-medium self-center">账号设置</div>
			<button
				class="self-center"
				on:click={() => {
					show = false;
				}}
			>
				<svg
					xmlns="http://www.w3.org/2000/svg"
					viewBox="0 0 20 20"
					fill="currentColor"
					class="w-5 h-5"
				>
					<path
						d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z"
					/>
				</svg>
			</button>
		</div>
		<hr class="border-gray-800" />

		<div class="flex flex-col md:flex-row w-full p-5 md:space-x-4">
			<div class="flex-1 md:min-h-[25rem]">
				<div class="flex flex-col h-full justify-between text-sm">
					<div class=" space-y-3 pr-1.5 overflow-y-scroll max-h-[22rem]">
						<input
							id="profile-image-input"
							bind:this={profileImageInputElement}
							type="file"
							hidden
							accept="image/*"
							on:change={(e) => {
								const files = profileImageInputElement.files ?? [];
								let reader = new FileReader();
								reader.onload = (event) => {
									let originalImageUrl = `${event.target.result}`;
				
									const img = new Image();
									img.src = originalImageUrl;
				
									img.onload = function () {
										const canvas = document.createElement('canvas');
										const ctx = canvas.getContext('2d');
				
										// Calculate the aspect ratio of the image
										const aspectRatio = img.width / img.height;
				
										// Calculate the new width and height to fit within 100x100
										let newWidth, newHeight;
										if (aspectRatio > 1) {
											newWidth = 100 * aspectRatio;
											newHeight = 100;
										} else {
											newWidth = 100;
											newHeight = 100 / aspectRatio;
										}
				
										// Set the canvas size
										canvas.width = 100;
										canvas.height = 100;
				
										// Calculate the position to center the image
										const offsetX = (100 - newWidth) / 2;
										const offsetY = (100 - newHeight) / 2;
				
										// Draw the image on the canvas
										ctx.drawImage(img, offsetX, offsetY, newWidth, newHeight);
				
										// Get the base64 representation of the compressed image
										const compressedSrc = canvas.toDataURL('image/jpeg');
				
										// Display the compressed image
										profileImageUrl = compressedSrc;
				
										profileImageInputElement.files = null;
									};
								};
				
								if (
									files.length > 0 &&
									['image/gif', 'image/jpeg', 'image/png'].includes(files[0]['type'])
								) {
									reader.readAsDataURL(files[0]);
								}
							}}
						/>
				
						<div class="space-y-1">
							<!-- <div class=" text-sm font-medium">{$i18n.t('Account')}</div> -->
				
							<div class="flex space-x-5">
								<div class="flex flex-col">
									<div class="self-center mt-2">
										<button
											class="relative rounded-full bg-gray-700"
											type="button"
											on:click={() => {
												profileImageInputElement.click();
											}}
										>
											<img
												src={profileImageUrl !== '' ? profileImageUrl : generateInitialsImage(name)}
												alt="profile"
												class=" rounded-full size-16 object-cover"
											/>
				
											<div
												class="absolute flex justify-center rounded-full bottom-0 left-0 right-0 top-0 h-full w-full overflow-hidden bg-gray-700 bg-fixed opacity-0 transition duration-300 ease-in-out hover:opacity-50"
											>
												<div class="my-auto text-gray-100">
													<svg
														xmlns="http://www.w3.org/2000/svg"
														viewBox="0 0 20 20"
														fill="currentColor"
														class="w-5 h-5"
													>
														<path
															d="m2.695 14.762-1.262 3.155a.5.5 0 0 0 .65.65l3.155-1.262a4 4 0 0 0 1.343-.886L17.5 5.501a2.121 2.121 0 0 0-3-3L3.58 13.419a4 4 0 0 0-.885 1.343Z"
														/>
													</svg>
												</div>
											</div>
										</button>
									</div>
								</div>
				
								<div class="flex-1 flex flex-col self-center gap-0.5">
									<div class=" mb-3 text-sm font-medium">头像</div>
				
									<div>
										<button
											class=" text-sm text-center rounded-full px-4 py-0.5 bg-gray-850"
											on:click={async () => {
												if (canvasPixelTest()) {
													profileImageUrl = generateInitialsImage(name);
												} else {
													toast.info(
														$i18n.t(
															'Fingerprint spoofing detected: Unable to use initials as avatar. Defaulting to default profile image.'
														),
														{
															duration: 1000 * 10
														}
													);
												}
											}}>{$i18n.t('Use Initials')}</button
										>
				
										<!-- <button
											class=" text-sm text-center rounded-full px-4 py-0.5 bg-gray-850"
											on:click={async () => {
												const url = await getGravatarUrl($user.email);
				
												profileImageUrl = url;
											}}>{$i18n.t('Use Gravatar')}</button
										>
				 -->
										<button
											class=" text-sm text-center rounded-lg px-2 py-1"
											on:click={async () => {
												profileImageUrl = '/user.png';
											}}>{$i18n.t('Remove')}</button
										>
									</div>
								</div>
							</div>
				
							<div class="pt-3">
								<div class="flex flex-col w-full">
									<div class=" mb-3 text-sm font-medium">用户名</div>
				
									<div class="flex-1">
										<input
											class="w-full rounded-lg py-2 px-4 text-sm bg-[#363A48] outline-none"
											type="text"
											bind:value={name}
											required
										/>
									</div>
								</div>
							</div>
						</div>
				
						<div class="py-3">
							<UpdatePassword />
						</div>
				
					</div>
				
					<div class="flex justify-end pt-3 text-sm font-medium">
						<button
							class="  px-4 py-2 bg-[#E95513] hover:bg-[#E95513] transition rounded-lg"
							on:click={async () => {
								const res = await submitHandler();
				
								if (res) {
									toast.success($i18n.t('Settings saved successfully!'));
								}
							}}
						>
							设置完成
						</button>
					</div>
				</div>
			</div>
		</div>
	</div>
</Modal>

<style>
	input::-webkit-outer-spin-button,
	input::-webkit-inner-spin-button {
		/* display: none; <- Crashes Chrome on hover */
		-webkit-appearance: none;
		margin: 0; /* <-- Apparently some margin are still there even though it's hidden */
	}

	input[type='number'] {
		-moz-appearance: textfield; /* Firefox */
	}
</style>
